export default {
    encode: encodeURIComponent,
    // 以便用户重写默认全局解码函数
    decode: decodeURIComponent,
    queryToJson: function (str, sep, eq) {
        //兼容最常用的 parse(location.search);
        var obj = {};
        str = str.replace(/^[^\?]*\?/, "");
        sep = sep || "&";
        eq = eq || "=";
        var arr, self = this, reg = new RegExp("(?:^|\\" + sep + ")([^\\" + eq + "\\" + sep + "]+)(?:\\" + eq + "([^\\" + sep + "]*))?", "g");
        while ((arr = reg.exec(str)) !== null) {
            if (arr[1] !== str) {
                obj[self.decode(arr[1])] = self.decode(arr[2] || "");
            }
        }

        return obj;
    },
    getParam: function (name, url) {
        if (url) {
            return this.queryToJson(url)[name];
        } else {
            if (!this.__queryCache) {
                this.__queryCache = this.queryToJson(location.search);
            }
            return this.__queryCache[name];
        }
    },
    param: function (obj, sep, eq) {
        var i, arr = [], self = this;
        sep = sep || "&";
        eq = eq || "=";
        for (i in obj) {
            if (obj.hasOwnProperty(i) && obj[i] !== null) {
                arr.push(self.encode(i) + (obj[i] === "" ? "" : eq + self.encode(obj[i])));
            }
        }
        return arr.join(sep);
    },
    deleteEmptyObject: function (obj) {
        for (var i in obj) {
            var value = obj[i];
            if (value === '' || value === null || value === 'undefined') {
                delete obj[i];
                console.log('delete ', i);
            }
        }
        return obj;
    },
    date: function (dateStr, format, options) {
        if (!dateStr) {
            return (new Date());
        }
        var obj = null;
        if (typeof dateStr === 'string' && /Date/.test(dateStr)) {
            var d = dateStr.replace(/\//g, '');
            obj = eval('(new ' + d + ')');
        } else {
            obj = typeof dateStr === 'string' ? new Date(dateStr.replace(/-/g, '/')) : dateStr;
        }

        var setting = {
            y: 0, //年
            M: 0, // 月
            d: 0, //日
            h: 0, //时
            m: 0, //分
            s: 0 //秒
        };

        $.extend(setting, options || {});

        obj = new Date(setting.y + obj.getFullYear(),
            setting.M + obj.getMonth(),
            setting.d + obj.getDate(),
            setting.h + obj.getHours(),
            setting.m + obj.getMinutes(),
            setting.s + obj.getSeconds());
        var o = {
            "M+": obj.getMonth() + 1,
            "d+": obj.getDate(),
            "h+": obj.getHours(),
            "m+": obj.getMinutes(),
            "s+": obj.getSeconds(),
            "q+": Math.floor((obj.getMonth() + 3) / 3),
            "S": obj.getMilliseconds()
        };
        if (format) {
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 4 ?
                        obj.getFullYear() :
                        (obj.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
                        o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
                }
            }
            return format;
        }
        else {
            return obj;
        }
    },
    tpl: function (template, data) {
        if (!template) {
            return;
        }
        template = template.replace(/%7B/gi, '{').replace(/%7D/gi, '}');

        var regex = /\{\$(\w+)\}/g,
            html = [];
        var replace = function (obj) {
            return template.replace(regex, function (str, match) {
                if (match in obj) {
                    return obj[match];
                }
                else {
                    return str;
                }
            });
        };

        if ($.isArray(data)) {
            for (var i = 0, len = data.length; i < len; i++) {
                var item = data[i];
                item._index = i;
                html.push(replace(item));
            }
        } else {
            html.push(replace(data));
        }
        return html.join('');

    },
    getCharCount: function (str) {
        if (str) {
            return str.replace(/[^\x00-\xff]/g, "xx").length;
        } else {
            return -1;
        }
    },
    subStr: function (str, len) {
        var newLength = 0,
            newStr = "",
            chineseRegex = /[^\x00-\xff]/g,
            singleChar = "",
            strLength = str.replace(chineseRegex, "**").length;
        for (var i = 0; i < strLength; i++) {
            singleChar = str.charAt(i).toString();
            if (singleChar.match(chineseRegex) !== null) {
                newLength += 2;
            }
            else {
                newLength++;
            }
            if (newLength > len) {
                break;
            }
            newStr += singleChar;
        }

        if (strLength > len) {
            newStr += "..";
        }
        return newStr;
    },
    storage: function (name, value) {
        if (value) {
            sessionStorage && sessionStorage.setItem(name, value);
        } else if (value === null) {
            sessionStorage && sessionStorage.removeItem(name);
        } else {
            if (sessionStorage) {
                return sessionStorage.getItem(name);
            } else {
                return '';
            }
        }
    },
    storageJSON: function (name, value) {
        if (value) {
            if (typeof value === 'object') {
                this.storage(name, JSON.stringify(value));
            } else {
                throw Error('storageJSON param require JSON');
            }
        } else {
            if (value === null) {
                this.storage(name, value);
            } else {
                var result = this.storage(name);
                return result ? JSON.parse(result) : null;
            }
        }
    },
    tab: function (options) {
        var opt = $.extend({
            el: '',
            selector: 'li',
            active: 'selected',
            index: 0,
            change: function () {
            }
        }, options || {});

        var $el = $(opt.el),
            $item = $el.find(opt.selector),
            curIndex = opt.index;

        $item.eq(curIndex).addClass(opt.active);
        opt.change && opt.change(curIndex, $item[curIndex]);

        $el.on('tap', opt.selector, function () {
            var i = $item.indexOf(this);
            if (i !== curIndex) {
                $item.eq(curIndex).removeClass(opt.active);
                $item.eq(i).addClass(opt.active);
                curIndex = i;
            }
            opt.change && opt.change(curIndex, $item[curIndex]);
        });
    }
}